use std::collections::HashMap;

use serde::{Deserialize, Serialize};

const FREQ_DEFAULT: u32 = 165000000;

#[derive(Serialize, Deserialize, Debug, PartialEq, Builder)]
#[builder(name = "PagerNumberInfoConstructor")]
pub struct PagerNumberInfo {
    #[builder(setter(into))]
    cap_code: String,
    #[builder(setter(into))]
    owner_name: String,
    #[serde(default = "freq_default")]
    frequency: u32,
}

fn freq_default() -> u32 {
    FREQ_DEFAULT
}

impl PagerNumberInfo {
    pub fn get_cap_code(&self) -> String {
        self.cap_code.clone()
    }

    pub fn get_frequency(&self) -> u32 {
        self.frequency
    }
}

#[derive(Serialize, Deserialize, Debug, PartialEq)]
pub struct PagerNumbers {
    pub items: HashMap<u16, PagerNumberInfo>,
}

impl PagerNumbers {
    pub fn get_info_to_send(&self, numb: u16) -> Option<&PagerNumberInfo> {
        self.items.get(&numb).and_then(Option::from)
    }

    pub fn get_info_pair(&self, numb: u16) -> Result<(String, u32), &'static str> {
        let y = self
            .get_info_to_send(numb)
            .ok_or("Number not found")
            .map(|arg| (arg.get_cap_code(), arg.get_frequency()));
        y
    }

    pub fn dumb(&self) -> String {
        serde_json::to_string(&self).unwrap()
    }

    pub fn subscribers(&self) -> String {
        let mut vk = vec![];
        for (k, v) in &self.items {
            vk.push(format!("{} - {}\n", k, v.owner_name))
        }
        vk.concat()
    }
}
